package io.finer.erp.jeecg.stock.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import io.finer.erp.jeecg.finance.vo.PurchaseOrderVO;
import io.finer.erp.jeecg.stock.entity.PurchaseOrder;
import io.finer.erp.jeecg.stock.entity.PurchaseOrderEntry;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.service.IPurchaseOrderEntryService;
import io.finer.erp.jeecg.stock.service.IPurchaseOrderService;
import io.finer.erp.jeecg.stock.vo.PurchaseOrderPage;
import io.finer.erp.jeecg.stock.vo.StkIoBillPage;
import io.finer.erp.jeecg.stock.vo.SupplierPriceVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 出入库单
 * @Author: jeecg-boot
 * @Date:   2021-05-20
 * @Version: V1.0
 */
@Api(tags="采购单")
@RestController
@RequestMapping("/stock/purchaseOrder")
@Slf4j
public class PurchaseOrderController {
	@Autowired
	private IPurchaseOrderService purchaseOrderService;
	@Autowired
	private IPurchaseOrderEntryService purchaseOrderEntryService;
	
	/**
	 * 分页列表查询
	 *
	 * @param purchaseOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出入库单-分页列表查询")
	@ApiOperation(value="出入库单-分页列表查询", notes="出入库单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PurchaseOrder purchaseOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PurchaseOrder> queryWrapper = QueryGenerator.initQueryWrapper(purchaseOrder, req.getParameterMap());
		queryWrapper.eq("stock_io_type", "601");
		Page<PurchaseOrder> page = new Page<PurchaseOrder>(pageNo, pageSize);
		IPage<PurchaseOrder> pageList = purchaseOrderService.page(page, queryWrapper);
		if(CollUtil.isNotEmpty(pageList.getRecords())) {
			List<String> idList = Lists.newArrayList();
			List<PurchaseOrder> records = pageList.getRecords();
			for (PurchaseOrder record : records) {
				idList.add(record.getId());
			}
			this.purchaseOrderService.list();
		}
		return Result.ok(pageList);
	}
	
	@AutoLog(value = "出入库单-分页列表查询-新方法")
	@ApiOperation(value="出入库单-分页列表查询-新方法", notes="出入库单-分页列表查询-新方法")
	@GetMapping(value = "/getPurchaseOrderList")
	public Result<IPage<PurchaseOrderVO>> getPurchaseOrderList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			   HttpServletRequest req){
		Page<PurchaseOrderVO> page = new Page<>(pageNo, pageSize);
		IPage<PurchaseOrderVO> pageList = purchaseOrderService.getPurchaseOrderList(page, req);
		Result<IPage<PurchaseOrderVO>> result = new Result<>();
		result.setResult(pageList);
		return result;
	}
	
	/**
	 * 采购单导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportPurchaseOrderXls"})  //stockIoType会传至stkIoBill.stockIoType
	public ModelAndView exportPurchaseOrderXls(HttpServletRequest request) {
		// Step.1 组装查询条件查询数据
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<PurchaseOrderVO> queryList = purchaseOrderService.getPurchaseOrderList(request);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<PurchaseOrderVO> list = new ArrayList<PurchaseOrderVO>();
		if(oConvertUtils.isEmpty(selections)) {
			list = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			list = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		//此处防止PurchaseOrderVO类里list是null时，导出报错null
		if(list!=null && list.size()>0) {
			for(PurchaseOrderVO vo:list) {
				if(vo.getList()==null || vo.getList().size()==0) {
					vo.setList(Lists.newArrayList());
				}
			}
		}
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "采购单");
		mv.addObject(NormalExcelConstants.CLASS, PurchaseOrderVO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购单", "导出人:"+sysUser.getRealname(), "采购单"));
		mv.addObject(NormalExcelConstants.DATA_LIST, list);
		return mv;
	}
	
	/**
	 *   添加
	 *
	 * @param purchaseOrderPage
	 * @return
	 */
	@AutoLog(value = "出入库单-添加")
	@ApiOperation(value="出入库单-添加", notes="出入库单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PurchaseOrderPage purchaseOrderPage) {
		PurchaseOrder purchaseOrder = new PurchaseOrder();
		BeanUtils.copyProperties(purchaseOrderPage, purchaseOrder);
		purchaseOrder.setStockIoType("601");
//		purchaseOrder.setBillProcStatus("12");
		List<PurchaseOrderEntry> entrys = purchaseOrderPage.getStkIoBillEntryTable();
		if(CollUtil.isEmpty(entrys)) {
			return Result.error("请添加明细！");
		}
		for (PurchaseOrderEntry entry : entrys) {
			entry.setWarehouseId("601HouseId");
			entry.setBillNo(purchaseOrder.getBillNo());
			entry.setSupplierId(purchaseOrder.getSupplierId());
		}
		purchaseOrder.setIsApproved(0);
		purchaseOrderService.saveMain(purchaseOrder, purchaseOrderPage.getStkIoBillEntryTable());
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param purchaseOrderPage
	 * @return
	 */
	@AutoLog(value = "出入库单-编辑")
	@ApiOperation(value="出入库单-编辑", notes="出入库单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PurchaseOrderPage purchaseOrderPage) {
		PurchaseOrder purchaseOrder = new PurchaseOrder();
		BeanUtils.copyProperties(purchaseOrderPage, purchaseOrder);
		PurchaseOrder purchaseOrderEntity = purchaseOrderService.getById(purchaseOrder.getId());
		if(purchaseOrderEntity == null) {
			return Result.error("未找到对应数据");
		}
		List<PurchaseOrderEntry> entrys = purchaseOrderPage.getStkIoBillEntryTable();
		if(CollUtil.isNotEmpty(entrys)) {
			for (PurchaseOrderEntry entry : entrys) {
				entry.setWarehouseId("601HouseId");
				entry.setSupplierId(purchaseOrder.getSupplierId());
				entry.setBillNo(purchaseOrder.getBillNo());
			}
		} else {
			return Result.error("请填写采购单明细");
		}
		purchaseOrderService.updateMain(purchaseOrder, purchaseOrderPage.getStkIoBillEntryTable());
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出入库单-通过id删除")
	@ApiOperation(value="出入库单-通过id删除", notes="出入库单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		purchaseOrderService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出入库单-批量删除")
	@ApiOperation(value="出入库单-批量删除", notes="出入库单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.purchaseOrderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出入库单-通过id查询")
	@ApiOperation(value="出入库单-通过id查询", notes="出入库单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PurchaseOrder purchaseOrder = purchaseOrderService.getById(id);
		if(purchaseOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(purchaseOrder);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "明细-通过主表ID查询")
	@ApiOperation(value="明细-通过主表ID查询", notes="明细-通过主表ID查询")
	@GetMapping(value = "/queryPurchaseOrderEntryByMainId")
	public Result<?> queryPurchaseOrderEntryListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PurchaseOrderEntry> purchaseOrderEntryList = purchaseOrderEntryService.selectByMainId(id);
		IPage <PurchaseOrderEntry> page = new Page<>();
		page.setRecords(purchaseOrderEntryList);
		page.setTotal(purchaseOrderEntryList.size());
		return Result.ok(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param purchaseOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PurchaseOrder purchaseOrder) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<PurchaseOrder> queryWrapper = QueryGenerator.initQueryWrapper(purchaseOrder, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<PurchaseOrder> queryList = purchaseOrderService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<PurchaseOrder> purchaseOrderList = new ArrayList<PurchaseOrder>();
      if(oConvertUtils.isEmpty(selections)) {
          purchaseOrderList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          purchaseOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<PurchaseOrderPage> pageList = new ArrayList<PurchaseOrderPage>();
      for (PurchaseOrder main : purchaseOrderList) {
          PurchaseOrderPage vo = new PurchaseOrderPage();
          BeanUtils.copyProperties(main, vo);
          List<PurchaseOrderEntry> purchaseOrderEntryList = purchaseOrderEntryService.selectByMainId(main.getId());
          vo.setStkIoBillEntryTable(purchaseOrderEntryList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "出入库单列表");
      mv.addObject(NormalExcelConstants.CLASS, PurchaseOrderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出入库单数据", "导出人:"+sysUser.getRealname(), "出入库单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<PurchaseOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PurchaseOrderPage.class, params);
              for (PurchaseOrderPage page : list) {
                  PurchaseOrder po = new PurchaseOrder();
                  BeanUtils.copyProperties(page, po);
                  purchaseOrderService.saveMain(po, page.getStkIoBillEntryTable());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }

    @GetMapping("/getSupplierPrice")
    @ApiOperation(value="获取供应商的该物料的价格", notes="获取供应商的该物料的价格")
    public Result<SupplierPriceVO> getSupplierPrice(@RequestParam(name="supplierId",required=true)String supplierId
    		,@RequestParam(name="materialId",required=true) String categoryId){
    	return this.purchaseOrderService.getSupplierPrice(supplierId, categoryId);
    }
    
    @PutMapping("/approve")
    @ApiOperation(value="采购单审批", notes="采购单审批")
    public Result<?> approve(@RequestBody PurchaseOrderPage order){
    	purchaseOrderService.approve(order);
    	return Result.ok("成功");
    }
    
    @AutoLog(value = "重新编辑采购单")
	@ApiOperation(value="重新编辑采购单", notes="重新编辑采购单")
	@PutMapping(value = "/reEdit")
	public Result<?> reEdit(@RequestBody PurchaseOrder purchaseOrder){
		LambdaQueryWrapper<PurchaseOrder> query = new LambdaQueryWrapper<>();
		query.eq(PurchaseOrder::getId, purchaseOrder.getBillId()).eq(PurchaseOrder::getStockIoType, "601");
		PurchaseOrder order = this.purchaseOrderService.getOne(query);
		if(null == order) {
			return Result.error(500, "未找到该采购单");
		}
		order.setBillProcStatus("12");
		order.setIsApproved(0);
		boolean flag = this.purchaseOrderService.updateById(order);
		if(flag) {
			return Result.ok("操作成功");
		} else {
			return Result.error(500, "操作失败");
		}
	}
}
